// pages/detail/detail.js
import { shareOptions } from "../../utils/access";
import request from "../../utils/request";
import tim from "../../utils/tim/tim";
import { getStorage, getTimUserId, jump } from "../../utils/utils"
const api = require("../../config/api");
const wxParse = require("../../utils/wxParse/wxParse.js");

Page({
	/**
	 * 页面的初始数据
	 */
	data: {
		arrdata: [],
		buyerFlag: false, //是否为买方
		phonePop: false,
		goodsId: "",
		goodsInfo: {},
		userId: "",
		labelName: "",
		ossImageList:"",
		goodsPrice:"",
		communityId:"",
		goodsDesc:"",
		goodsClassifyId:"",
		goodsSubClassifyId:"",
		goodsSigns:"",
		id:0,
		recommendList:[] //猜你喜欢数据
	},

	// 更新商品浏览次数
	async updateViewsTimes(){
		let id= this.data.goodsId
    await request.post(api.updateViewsTimes, { id }, {loading: false} )
	},
	async getGoodsDetail(id) {
		let { userId } = this.data;
		const res = await request.get(api.goodsDetail, { id }, { loading: false });
		console.log("PPPPPP",res);
		this.setData({
			goodsInfo: res?.data,
			labelName: res?.data.goodsSigns.length
				? res?.data.goodsSigns.join(",").replace(/(,|#)/g, " ")
				: "",
				ossImageList:res?.data.urls,
				goodsPrice:res?.data.goodsPriceY,
				communityId:res?.data.communityId,
				goodsDesc:res?.data.goodsDesc,
				goodsClassifyId:res?.data.goodsClassifyId,
				goodsSubClassifyId:res?.data.goodsSubClassifyId,
				goodsSigns:res?.data.goodsSigns,
				id:res?.data.id,
		});

		if (userId == res.data.userId) {
			this.setData({
				buyerFlag: false,
			});
		} else {
			this.setData({
				buyerFlag: true,
			});
			this.getGoodsRecommend()
		}
	},
	
	/**
	 * 获取猜你喜欢数据
	 */
	async getGoodsRecommend(){
		let communityId= getStorage('communityId')
		let goodsClassifyId= this.data.goodsInfo.goodsClassifyId
		const res= await request.get(api.recommendGoods, { 
			communityId,
      goodsClassifyId,
		}, { loading: false })
		this.setData({
			recommendList: res?.data || []
		})
	},

	hadneleSoldOut() {
		let id = this.data.goodsInfo.id;
		let _this = this;
		wx.showModal({
			title: "温馨提示",
			content: "确认要下架该商品吗？",
			success: function (res) {
				if (res.confirm) {
					_this.goodsSoldOutItem(id);
				}
			},
		});
	},
	async goodsSoldOutItem(id) {
		const res = await request.post(
			api.goodsShelves,
			{
				id,
			},
			{ loading: false }
		);

		if (res.httpStatus == 200) {
			wx.showToast({
				title: "下架成功!",
			});
			this.getGoodsDetail(id);
		}
	},

	hadneleGodEdit(e) {
		console.log(e.currentTarget.dataset.item.id);
		wx.navigateTo({
			url: `/pages/idleRelease/idleRelease?goodsId=${e.currentTarget.dataset.item.id}`,
		});
	},
	// 展示草稿保存提示
async	showDraftModal(params){
	wx.showModal({
		title: '提示',
		content: '是否保存草稿？',
		confirmText: '保存',
		cancelText: '不保存',
		async	success(res) {
			 if (res.confirm) { //保存草稿
			 let res= await request.post(api.addTempGoods, params,{loading: true})
			 if(res.httpStatus=== 200){
				wx.showToast({
					title: '保存成功',
					icon: 'none'
				})
			 }
			} else if (res.cancel) {//删除草稿
				if(!params.id) return //没有草稿
				let res= await request.post(api.deleteTempGoods, {id: params.id},{loading: true})
				 if(res.httpStatus=== 200){
					wx.showToast({
						title: '删除成功',
						icon: 'none'
					})
				}
			}
		}
	})
},
	async handleTakePhone() {
		let { id, userId } = this.data.goodsInfo;
		const sourceUserId = getStorage("userId");
		const res = await request.get(
			api.getContactPhone,
			{
				sourceId: id,
				sourceUserId,
				targetUserId: userId,
				type: 10,
			},
			{ loading: false }
		);
		wx.makePhoneCall({
			phoneNumber: res.data,
		});
	},
	//收藏
	async handlecCllect() {
		let id = this.data.goodsInfo.id;
		const res = await request.post(api.collect, { id }, { loading: false });

		if (res?.httpStatus == 200) {
			this.getGoodsDetail(id);
		}
	},
	//取消收藏
	async handlecCencelCllect() {
		let id = this.data.goodsInfo.id;
		const res = await request.post(
			api.cancelCollection,
			{ id },
			{ loading: false }
		);
		if (res?.httpStatus == 200) {
			this.getGoodsDetail(id);
		}
	},

	//重新发布
	async hadneleGodRelease(){
		let {
			ossImageList,
			goodsPrice,
			communityId,
			goodsDesc,
			goodsClassifyId,
			goodsSubClassifyId,
			goodsSigns,
			id,
		} = this.data;
		if (ossImageList.length <= 0) {
			wx.showToast({
				title: "请上传图片!",
				icon: "none",
				duration: 2000,
			});
			return;
		}
		if (!goodsPrice) {
			wx.showToast({
				title: "请输入价格!",
				icon: "none",
				duration: 2000,
			});
			return;
		}

		if (!communityId) {
			wx.showToast({
				title: "请选择地址!",
				icon: "none",
				duration: 2000,
			});
			return;
		}
		if (!goodsClassifyId&&!goodsSubClassifyId) {
			wx.showToast({
				title: "请选择类型!",
				icon: "none",
				duration: 2000,
			});
			return;
		}

		if (goodsPrice <= 0 || goodsPrice == ".") {
			wx.showToast({
				title: "价格区间0.1~999999.9",
				icon: "none",
				duration: 2000,
			});
			return;
		}

		wx.showLoading({
			title: "商品信息校验中",
			icon: "loading",
			duration: 10000,
			mask: true,
		});

		const res = await request.post(
			api.goodsRelease,
			{
				urls: ossImageList,
				goodsPrice: goodsPrice,
				communityId,
				goodsDesc,
				goodsClassifyId: goodsClassifyId || "",
				goodsSubClassifyId: goodsSubClassifyId,
				goodsSigns: goodsSigns || [],
				id:id,
			},
			{
				loading: false,
			}
		);
		if (res?.httpStatus == 200) {
			var pages = getCurrentPages(); //当前页面
			var beforePage = pages[pages.length - 2]; //前一页
			beforePage.onLoad(); // 执行前一个页面的onLoad方法
			wx.navigateBack({
				delta: 1,
			});
			wx.hideLoading();
		} else {
			wx.hideLoading();
			wx.showToast({
				title: res.msg,
				icon: "none",
				duration: 2000,
			});
		}
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function (options) {
		const userId = getStorage("userId");
		this.setData({
			goodsId: options.goodsId,
			userId,
		});
		wx.setNavigationBarColor({
			frontColor: "#000000",
			backgroundColor: "#f5f5f5",
		});
		this.updateViewsTimes()
	},
	handleDelete() {
		let _this = this;
		let id = this.data.goodsInfo.id;
		wx.showModal({
			title: "温馨提示",
			content: "确认要删除该商品吗？",
			success: function (res) {
				if (res.confirm) {
					_this.goodsDeleteItem(id);
				}
			},
		});
	},
	async goodsDeleteItem(id) {
		const res = await request.post(api.goodsDelete, { id }, { loading: false });
		if (res?.httpStatus == 200) {
			var pages = getCurrentPages();
			var beforePage = pages[pages.length - 2];
			beforePage.onLoad();
			wx.navigateBack({
				delta: 1,
			});
		}
	},

	async handelShare() {
		const res = await request.post(api.idleShare, {}, { loading: false });
	},

	async handelePhonePop() {
		if (this.loading) return
		this.loading = true
		const isTimLogin = await tim.login()
		if (isTimLogin) {
			const userId = getTimUserId(this.data.goodsInfo.userId)
			const res = await tim.getUser(userId)
			if (res) {
				jump('chat', {
					conversationID: `C2C${userId}`,
				}, {
					complete: () => {
						this.loading = false
					}
				})
			} else {
				this.loading = false
			}
		} else {
			wx.showToast({
        icon: 'none',
        title: '您还没有登录im',
      })
			this.loading = false
		}
		// this.setData({ phonePop: true });
	},
	handleClonePop() {
		this.setData({ phonePop: false });
	},
	handleGoodsBuy() {
		let id = this.data.goodsInfo.id;
		wx.navigateTo({
			url: `/pages/idleAddOrder/idleAddOrder?id=` + id,
		});
	},

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function () {},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function () {
		this.getGoodsDetail(this.data.goodsId);
	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function () {},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function () {},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function () {},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function () {},

	// 用户点击右上角分享
	onShareAppMessage(e) {
		let { goodsInfo } = this.data
		return shareOptions('default', e, goodsInfo.goodsDesc ? goodsInfo.goodsDesc : '发现个宝贝，快来看看吧', '/pages/convenience/convenience?inviteData=' + getStorage('userId'), goodsInfo.urls[0])
	},
});
